package accs.model.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import accs.model.UserPasswordPair;

public class RegexUserPasswordReader extends UserPasswordReader {
	private BufferedReader reader;
	private Pattern pattern;
	private int userGroup;
	private int passGroup;
	
	public RegexUserPasswordReader(Reader reader, Pattern pattern, int userGroup, int passGroup) {
		this.reader=new BufferedReader(reader);
		this.pattern=pattern;
		this.userGroup=userGroup;
		this.passGroup=passGroup;
	}

	public UserPasswordPair read() throws IOException {
		String line=null;
		Matcher match=null;
		
		while((line=reader.readLine())!=null && !(match=pattern.matcher(line)).matches()) {}
		if(line==null) return null;
		
		return new UserPasswordPair(match.group(userGroup),match.group(passGroup));
	}

	public void close() throws IOException {
		reader.close();
	}
}